package com.xhc.demo.repository;

import com.xhc.demo.entity.Order;
import com.xhc.demo.entity.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Repository
public interface OrderRepository extends JpaRepository<Order, Long> {
    List<Order> findByUser(User user);
    Order findByOrderNumber(String orderNumber);
    
    Optional<Order> findByOrderIdAndPayOrderNumber(Long orderId, String payOrderNumber);
    
    List<Order> findByUserOrderByOrderTimeDesc(User user);
    
    // 获取待付款订单数量（actualAmount为null或为0的订单）
    @Query("SELECT COUNT(o) FROM Order o WHERE o.user = :user AND (o.actualAmount IS NULL OR o.actualAmount = 0)")
    Long countPendingPaymentOrders(@Param("user") User user);
    
    // 获取待收货订单数量（状态不是SIGNED且actualAmount不为null且不为0的订单）
    @Query("SELECT COUNT(o) FROM Order o WHERE o.user = :user AND o.status != 'SIGNED' AND o.actualAmount IS NOT NULL AND o.actualAmount > 0")
    Long countPendingDeliveryOrders(@Param("user") User user);

    // 获取所有待付款订单，按下单时间倒序排序
    @Query("SELECT o FROM Order o WHERE o.user = :user AND (o.actualAmount IS NULL OR o.actualAmount = 0) ORDER BY o.orderTime DESC")
    List<Order> findAllPendingPaymentOrders(@Param("user") User user);

    // 获取已支付待收货订单（分页）
    @Query("SELECT o FROM Order o WHERE o.user = :user AND o.actualAmount IS NOT NULL AND o.actualAmount > 0 AND o.status != 'SIGNED' ORDER BY o.orderTime DESC")
    Page<Order> findPaidOrdersWithPagination(@Param("user") User user, Pageable pageable);

    // 获取所有已支付订单（分页）
    @Query("SELECT o FROM Order o WHERE o.user = :user AND o.actualAmount IS NOT NULL AND o.actualAmount > 0 ORDER BY o.orderTime DESC")
    Page<Order> findAllPaidOrdersWithPagination(@Param("user") User user, Pageable pageable);

    // 获取所有订单（分页）
    @Query("SELECT DISTINCT o FROM Order o " +
           "LEFT JOIN FETCH o.user u " +
           "LEFT JOIN FETCH o.address a " +
           "LEFT JOIN FETCH o.photos p " +
           "WHERE (o.orderNumber IS NULL OR o.orderNumber = '') " +
           "AND o.actualAmount IS NOT NULL AND o.actualAmount > 0")
    Page<Order> searchOrders(
            Pageable pageable);
}
